package com.woniuxy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @Author: 马宇航
 * @Todo: 处理文件上传和下载的控制器
 * @DateTime: 22/02/11/0011 上午 11:31
 * @Component: 成都蜗牛学苑
 **/
@Controller
@RequestMapping("/file")
public class FileUploadDownloadController {
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam("file") MultipartFile file, String description, Model model){
        //通常，我们在企业开发，是不这么写的，都是使用云OSS服务，比如：七牛云，或者阿里云的OSS服务
        //判断上传文件是否为空
        if (!file.isEmpty()){
            //上传文件的路径
            String realPath = request.getServletContext().getRealPath("/files/");
            System.out.println("文件上传路径"+realPath);
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            File file1 = new File(realPath, originalFilename);
            //判断路径是否存在
            if (!file1.getParentFile().exists()){
                file1.getParentFile().mkdirs();
            }
            try {
                file.transferTo(new File(realPath+File.separator+originalFilename));
                model.addAttribute("msg","文件上传成功路径是："+realPath+File.separator+file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
     return "success";
    }
}
